package com.write.ibatis.session.impl;

import com.write.ibatis.bing.MapperProxy;
import com.write.ibatis.config.Configuration;
import com.write.ibatis.executor.Executor;
import com.write.ibatis.session.SqlSession;

import java.lang.reflect.Proxy;
import java.util.List;

public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;
    private Executor executor;

    public DefaultSqlSession(Configuration configuration, Executor executor) {
        this.configuration = configuration;
        this.executor = executor;
    }

    @Override
    public <T> T selectOne(String statement, Object parameter) {
        List<T> list = executor.query(configuration.getMapperStatement(statement), parameter);
        if(list!=null&& list.size()>0){
            return list.get(0);
        }
        return null;
    }

    @Override
    public <E> List<E> selectList(String statement) {
        return executor.query(configuration.getMapperStatement(statement),null);
    }

    @Override
    public <E> List<E> selectList(String statement, Object parameter) {
        return executor.query(configuration.getMapperStatement(statement),parameter);
    }

    @Override
    public Configuration getConfiguration() {
        return this.configuration;
    }

    @Override
    public <T> T getMapper(Class<T> type) {
        //获取接口代理对象
        T mapperProxy = (T)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{type}, new MapperProxy(this));
        return mapperProxy;
    }
}
